package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Menu;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Reference
    private UserService userService;


    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}", param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        //用户不存在或密码不匹配则登录失败
        if (null == user || !user.getPassword().equals(param.getPassword())) {
            log.info("[登录]失败，user:{}", param.getUsername());

            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        //模拟用户登录成功
        log.info("[登录]成功，user:{}", user.getUsername());
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }


    /**
     * 修改用户密码
     *
     * @param param
     * @return
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody LoginParam param) {
        log.info("[登录]data:{}", param);
        BCryptPasswordEncoder b = new BCryptPasswordEncoder();
        User user = userService.findByUsername(param.getUsername());

        if (!b.matches(param.getPassword(),user.getPassword())) {
            return new Result(false, "用户名或密码错误");

        }
        //String encodePassword = b.encode(param.getPassword());
        String encodeNewPassword = b.encode(param.getNewPassword());
        userService.updatePassword(param.getUsername(), encodeNewPassword);

        return new Result(true, "密码修改成功");
    }

    /**
     * 获取当前登录用户名
     *
     * @return
     */
    @GetMapping("/getUserDetail")
    public Result getUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null != principal && principal instanceof org.springframework.security.core.userdetails.User) {
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) principal;

            //查询登陆状态成功，先根据username查询出User
            User userReal = userService.findByUsername(user.getUsername());
            //根据userReal查询其权限对应的菜单信息，并封装返回

            User userWithMenu = userService.findMenuByUser(userReal);
            log.info("User:{}",userWithMenu);



            LinkedHashSet<Menu> menuSet = new LinkedHashSet<>();
            for (Role role : userWithMenu.getRoles()) {
                menuSet.addAll(role.getMenus());
            }




            log.info("meneSet:{}",menuSet);
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS,menuSet);
        }
        return new Result(false, MessageConst.GET_USERNAME_FAIL);
    }



    @RequestMapping("/loginSuccess")
    public Result loginSuccess() {
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }




    @RequestMapping("/loginFail")
    public Result loginFail() {
        return new Result(false, "登录失败");
    }


    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(QueryPageBean queryPageBean){
        log.info("[用户-分页查询]data:{}", queryPageBean);
        //调用DAO层查询并返回
        PageResult pageResult = userService.findPage(queryPageBean);
        //构造返回结果并返回
        return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,pageResult);
    }

    /**
     * 增加用户
     * @param user
     * @param roles
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user,Integer[] roles){
        log.info("[用户-添加]data:{},roles:{}", user, roles);
        //rpc增加
        userService.add(user,roles);
        //返回结果
        return new Result(true,MessageConst.ACTION_SUCCESS);
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Result findById(Integer id){
        log.info("[用户-根据id查询]id:{}", id);
        //rpc查询
        User user = userService.findById(id);
        //返回结果
        return new Result(true,MessageConst.ACTION_SUCCESS,user);
    }

    /**
     * 根据用户id查询角色id
     * @param id
     * @return
     */
    @GetMapping("/findRoleIdByUserId")
    public Result findRoleIdByUserId(Integer id){
        log.info("[角色-根据用户id查询关联的角色id集和]id:{}", id);
        //rpc查询
        List<Integer> roleIds = userService.findRoleIdByUserId(id);
        //返回结果
        return new Result(true,MessageConst.ACTION_SUCCESS,roleIds);
    }

    /**
     * 编辑用户
     * @param user
     * @param roles
     * @return
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody User user,Integer[] roles){
        log.info("[用户-编辑]data:{},checkitemIds:{}", user, roles);
        //rpc查询结果
        userService.editByUserAndRoleIds(user,roles);
        //返回结果
        return new Result(true,MessageConst.ACTION_SUCCESS);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public Result delete(Integer id){
        //rpc调用
        userService.deleteById(id);
        //返回结果
        return new Result(true,MessageConst.ACTION_SUCCESS);
    }

    /**
     * 检查用户名是否重复
     * @param username
     * @return
     */
    @GetMapping("/checkUsername")
    public Result checkUsername(String username){
        log.info("[用户名-检查]username:{}", username);
        if(null == username || username == ""){
            return new Result(false,"用户名不能为空");
        }
        //DAO查询
        User user = userService.checkUsername(username);
        if(user == null){
            return new Result(true,"√");
        }
            return new Result(false,"用户名不能重复");

    }
}
